package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;

/**
 * <pre>
 * FORMAT(X,D)
 *
 * Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result setAliasAndSetNeedBuild a string. If D is 0, the result has no decimal point or fractional part.
 *
 * mysql> SELECT FORMAT(12332.123456, 4);
 *         -> '12,332.1235'
 * mysql> SELECT FORMAT(12332.1,4);
 *         -> '12,332.1000'
 * mysql> SELECT FORMAT(12332.2,0);
 *         -> '12,332'
 *
 *
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月15日 下午5:50:13
 * @since 5.1.0
 */
public class Format extends ScalarFunction {

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"FORMAT"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        BigDecimal X = Type.BigDecimalType.convert(args[0]);

        Integer D = Type.IntegerType.convert(args[1]);

        NumberFormat nf = NumberFormat.getInstance(Locale.US);
        nf.setGroupingUsed(true);
        nf.setMaximumFractionDigits(D);
        nf.setMinimumFractionDigits(D);
        return nf.format(X);

    }

}
